
package com.cn.ycy.config.interceptor;


import com.cn.ycy.controller.PageHelperController;
import com.cn.ycy.dto.User;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class SecurityInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            return true;
        }

        boolean exists = false;
        String auth = null;
        auth = request.getHeader("token");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    auth = cookie.getValue();
                }
            }
        }

        if (!StringUtils.isBlank(auth)) {
            User user = PageHelperController.loginToken.get(auth);
            if (user != null) {
                SecureUtil.setCurrentEmbedUser(user);
                exists = true;
            } else {
                log.warn("token is not exists or expired!token:{}", auth);
            }
        } else {
            log.warn("token is not exists or expired!token:{}", auth);
        }


        if (!exists) {
//            log.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}，请求token:{}，返回码:{}", new Object[]{request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()), auth, responseCode});
            log.warn("签名认证失败，请求接口：");
            try {
                response.setCharacterEncoding("UTF-8");
                response.sendError(HttpStatus.FORBIDDEN.value(), "拒绝访问，没有访问权限：" + request.getRequestURI());
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
            return false;
        }



        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("finish afterCompletion");
    }
}

